#include <stdlib.h>
#include <string.h>

#include "Error.h"
#include "File.h"
#include "Filing.h"

#include "appglobal.h"
#include "fsutils.h"
#include "log.h"

char *fsutils_canonicalise_path(const char *in_path, BOOL report)
{
  char *buffer = NULL;
  int spare;
  os_error *e = Filing_CanonicalisePath((char *) in_path, buffer, 0, &spare);

  if (e)
  {
    if (report)
    {
      Error_Check(e);
    }
    return NULL;
  }
  buffer = malloc(1 - spare);
  e = Filing_CanonicalisePath((char *) in_path, buffer, 1 - spare, &spare);
  if (e || spare != 1)
  {
    if (e && report)
    {
      Error_Check(e);
    }
    free(buffer);
    return NULL;
  }
  return buffer;
}

char *fsutils_strdup(const char *s1)
{
  char *s2;

  if (!s1)
    return NULL;

  s2 = malloc(strlen(s1) + 1);
  if (s2)
    strcpy(s2, s1);
  else
    Error_Report(0, MSG_NOMEM);
  return s2;
}

BOOL fsutils_mkdir(const char *name)
{
  os_error *e;

  LOG("Creating directory %s\n", name);

  e = SWI(5, 0, SWI_OS_File, 8, name, NULL, NULL, 0);
  if (e)
  {
    char *leaf;
    char *parent = fsutils_strdup(name);

    if (!parent)
      return FALSE;
    leaf = strrchr(parent, '.');
    if (!leaf)
      return !Error_Check(e);
    *leaf = 0;
    return fsutils_mkdir(name);
  }

  return TRUE;
}

BOOL fsutils_copy(const char *source, const char *dest)
{
  LOG("Copying %s to %s\n", source, dest);
  return !Error_Check(SWI(4, 0, SWI_OS_FSControl, 26, source, dest,
                          1 | (1<<1) | (1<<12) ));
}

BOOL fsutils_wipe(const char *file)
{
  LOG("Wiping %s\n", file);
  return !Error_Check(SWI(4, 0, SWI_OS_FSControl, 27, file, 0, 1 | (1<<1) ));
}

os_error *fsutils_set_dir(const char *dir)
{
  LOG("Setting CSD to %s\n", dir);
  return SWI(2, 0, SWI_OS_FSControl, 0, dir);
}
